import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import Login from '@/views/login'
import Layout from '@/views/layout'
import Home from '@/views/home'
import Question from '@/views/question'
import Video from '@/views/video'
import User from '@/views/user'
import Search from '@/views/search'
import SearchResult from '@/views/searchResult'
import Article from '@/views/article'
import UserProfile from '@/views/user/profile.vue'
import UserChat from '@/views/userChat'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        // meta就是个标识，在app页标示需要缓存
        { path: '', component: Home, meta: { isKeepAlive: true } },
        { path: 'question', component: Question },
        { path: 'video', component: Video },
        { path: 'user', component: User }
      ]
    },
    { path: '/search', component: Search },
    { path: '/searchResult', component: SearchResult },
    { path: '/article/:id', component: Article },
    { path: '/userProfile', component: UserProfile },
    { path: '/userChat', component: UserChat }
  ]
})

// 需要认证的页面
const AuthUrls = ['/user', '/cart']
router.beforeEach((to, from, next) => {
  // 在 登录被真正访问前，也会经过全局前置守卫，判断有没有token
  // 只要有token就放进首页，如果真是过期的token，那么在响应拦截器中也会处理，refresh_token过期，
  // 也会清除过期的token
  // 要授权的页面，判断是否有token
  const token = store.state.tokenInfo.token
  // 如果发现过期的token，一定要清
  if (to.path === '/login' && token) {
    // 登录过了，放行，直接去首页
    next('/')
    return
  }
  // 判断要去的页面，是否需要授权
  if (AuthUrls.includes(to.path)) {
    // 进行验证身份 有token
    if (token) {
      next()
    } else {
      // 拦截登录 没有 token就拦截到登录
      next({
        path: '/login',
        query: {
          a: 1,
          b: 2,
          backto: to.fullPsath
        }
      })
    }
  } else {
    // 不需要授权即可访问
    next()
  }
})

export default router
